package com.yj.mvc.web.servlet.view;

import cn.hutool.json.JSONUtil;
import com.yj.mvc.web.core.MappingValue;
import com.yj.mvc.web.servlet.resource.WebXmlResourceParse;
import com.yj.mvc.web.servlet.resource.XmlConfigReader;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class DispatcherServlet{


    Map<String, MappingValue> mappingValues = new HashMap<>();

    Map<String, Class<?>> mappingClz = new HashMap<>();

    Map<String, Object> mappingObj = new HashMap<>();

    private static Logger logger = Logger.getLogger(DispatcherServlet.class.getName());

    private ServletConfig servletConfig;

    public void init(ServletConfig servletConfig) throws ServletException {
        // 初始化映射关系
        // 1. 读取配置文件
        // 2. 解析配置文件
        // 3. 保存映射关系
        this.servletConfig = servletConfig;
        logger.info("servletConfig = " + JSONUtil.toJsonStr(servletConfig));
    }

    public ServletConfig getServletConfig() {
        return this.getServletConfig();
    }

    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {

        // 根据请求路径，找到对应的处理类
        // 1. 根据请求路径，从映射关系中获取处理类
        // 2. 实例化处理类
        // 3. 调用处理类的方法，处理请求
        // 4. 根据不同的请求，返回不同的响应
    }

    public String getServletInfo() {
        return null;
    }

    public void destroy() {
        // 销毁
    }

    public static void main(String[] args) {
        ServletContext customServletContext = new CustomServletContext();
        ServletConfig customServletConfig = new CustomServletConfig(customServletContext);
        WebXmlResourceParse webXmlResourceParse = new WebXmlResourceParse("resource/web.xml");
        webXmlResourceParse.setServletConfig(customServletConfig);

        XmlConfigReader xmlConfigReader = new XmlConfigReader(customServletConfig);
        xmlConfigReader.loadConfig();


    }
}
